package com.ungao.servlet;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpPrincipal;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class HttpServletRequest {

    private Headers requestHeaders;
    private URI requestURI;
    private String requestMethod;
    private InputStream requestBody;
    private InetSocketAddress remoteAddress;
    private InetSocketAddress localAddress;
    private String protocol;
    private HttpPrincipal principal;
    private Map<String, Object[]> parameterMap;

    public HttpServletRequest(HttpExchange httpExchange) {
        this.requestHeaders = httpExchange.getRequestHeaders();
        this.requestHeaders = httpExchange.getRequestHeaders();
        this.requestURI = httpExchange.getRequestURI();
        this.requestMethod = httpExchange.getRequestMethod();
        this.requestBody = httpExchange.getRequestBody();
        this.remoteAddress = httpExchange.getRemoteAddress();
        this.localAddress = httpExchange.getLocalAddress();
        this.protocol = httpExchange.getProtocol();
        this.principal = httpExchange.getPrincipal();
        String rawQuery = httpExchange.getRequestURI().getQuery();
        if (rawQuery != null && rawQuery != "") {
            String[] items = rawQuery.split("&");
            this.parameterMap = new ConcurrentHashMap<>(items.length);
            for (String item : items) {
                String[] keyValue = item.split("=");
                Object[] values = this.parameterMap.getOrDefault(keyValue[0], new Object[]{keyValue[1]});
                values = Arrays.copyOf(values, values.length + 1);
                values[values.length - 1] = keyValue[1];
                this.parameterMap.put(keyValue[0], values);
            }
        }
    }

    public Headers getRequestHeaders() {
        return this.requestHeaders;
    }

    public URI getRequestURI() {
        return this.requestURI;
    }

    public String getRequestMethod() {
        return this.requestMethod;
    }

    public InputStream getRequestBody() {
        return this.requestBody;
    }

    public InetSocketAddress getRemoteAddress() {
        return this.remoteAddress;
    }

    public InetSocketAddress getLocalAddress() {
        return this.localAddress;
    }

    public String getProtocol() {
        return this.protocol;
    }

    public HttpPrincipal getPrincipal() {
        return this.principal;
    }

    public Map<String, Object[]> getParameterMap() {
        return this.parameterMap;
    }
}
